package org.openea.eap.module.obpm.controller.form;

import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.exception.BusinessException;
import org.openbpm.base.api.query.QueryFilter;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.core.util.ThreadMapUtil;
import org.openbpm.base.dao.CommonDao;
import org.openbpm.base.db.datasource.DbContextHolder;
import org.openbpm.base.db.model.page.PageResult;
import org.openbpm.base.db.model.table.Column;
import org.openbpm.base.db.model.table.Table;
import org.openbpm.base.rest.BaseController;
import org.openbpm.base.rest.util.RequestUtil;
import org.openea.eap.module.obpm.service.form.FormCustDialogManager;
import org.openea.eap.module.obpm.model.form.FormCustDialog;
import org.openbpm.sys.api.model.ISysDataSource;
import org.openbpm.sys.api.service.ISysDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping({"/form/formCustDialog/"})
public class FormCustDialogController
        extends BaseController<FormCustDialog> {
    @Autowired
    FormCustDialogManager formCustDialogManager;
    @Autowired
    CommonDao<?> commonDao;
    @Autowired
    ISysDataSourceService sysDataSourceService;

    @RequestMapping({"getObject"})
    @CatchErr(write2response = true, value = "获取formCustDialog异常")
    public ResultMsg<FormCustDialog> getObject(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = RequestUtil.getString(request, "id");
        String key = RequestUtil.getString(request, "key");
        FormCustDialog formCustDialog = null;
        if (StringUtil.isNotEmpty(id)) {
            formCustDialog = (FormCustDialog) this.formCustDialogManager.get(id);
        } else if (StringUtil.isNotEmpty(key)) {
            formCustDialog = this.formCustDialogManager.getByKey(key);
        }

        return getSuccessResult(formCustDialog);
    }


    @RequestMapping({"searchObjName"})
    @CatchErr(write2response = true, value = "根据数据源获取objName信息失败")
    public ResultMsg<Map<String, String>> searchObjName(HttpServletRequest request, HttpServletResponse response, @RequestBody FormCustDialog formCustDialog) throws Exception {
        return getSuccessResult(this.formCustDialogManager.searchObjName(formCustDialog), "根据数据源获取objName信息成功");
    }


    @RequestMapping({"getTable"})
    @CatchErr(write2response = true, value = "根据数据源获取objName的字段信息失败")
    public ResultMsg<Table<Column>> getTable(HttpServletRequest request, HttpServletResponse response, @RequestBody FormCustDialog formCustDialog) throws Exception {
        return getSuccessResult(this.formCustDialogManager.getTable(formCustDialog), "根据数据源获取objName的字段信息成功");
    }


    @RequestMapping({"listData_{key}"})
    @CatchErr(write2response = true, value = "获取对话框的列表数据失败")
    public PageResult listData(HttpServletRequest request, HttpServletResponse response, @PathVariable("key") String key) throws Exception {
        boolean isPage = (request.getParameter("limit") != null);
        ThreadMapUtil.put("isPage", Boolean.valueOf(isPage));

        FormCustDialog formCustDialog = this.formCustDialogManager.getByKey(key);
        if(formCustDialog==null){
            throw new BusinessException("对话框 "+key+ " 不存在");
        }
        QueryFilter queryFilter = getQueryFilter(request);
        ISysDataSource sysDataSource = this.sysDataSourceService.getByKey(formCustDialog.getDsKey());

        if (sysDataSource != null) {
            DbContextHolder.setDataSource(sysDataSource.getKey(), sysDataSource.getDbType());
        }
        List<?> list = this.formCustDialogManager.data(formCustDialog, queryFilter);

        ThreadMapUtil.remove();
        return new PageResult(list);
    }


    @RequestMapping({"queryListData_{key}"})
    @CatchErr(write2response = true, value = "获取对话框的列表数据失败")
    public PageResult qlistData(HttpServletRequest request, HttpServletResponse response, @PathVariable("key") String key) throws Exception {
        FormCustDialog formCustDialog = this.formCustDialogManager.getByKey(key);
        if(formCustDialog==null){
            throw new BusinessException("对话框 "+key+ " 不存在");
        }
        formCustDialog.getConditionFields().forEach(field -> {
            Object val = request.getParameter(field.getColumnName());
            if (val == null) {
                return;
            }
            String str = field.getColumnName() + "$" + field.getDbType().substring(0, 1).toUpperCase() + field.getCondition();
            request.setAttribute(str, val);
        });

        PageResult pageResult = listData(request, response, key);
        List<Map<String, Object>> rows = new ArrayList<>();
        pageResult.getRows().forEach(row -> {
            Map<String, Object> map = (Map<String, Object>) row;
            Map<String, Object> m = new HashMap<>();
            formCustDialog.getReturnFields().forEach(field -> {
                m.put(field.getReturnName(), map.get(field.getColumnName()));
            });
            rows.add(m);
        });
        pageResult.setRows(rows);
        return pageResult;
    }


    @RequestMapping({"treeData_{key}"})
    public List<?> treeData(HttpServletRequest request, HttpServletResponse response, @PathVariable("key") String key) throws Exception {
        QueryFilter queryFilter = getQueryFilter(request);
        queryFilter.setPage(null);

        FormCustDialog formCustDialog = this.formCustDialogManager.getByKey(key);
        ISysDataSource sysDataSource = this.sysDataSourceService.getByKey(formCustDialog.getDsKey());

        DbContextHolder.setDataSource(sysDataSource.getKey(), sysDataSource.getDbType());
        return this.formCustDialogManager.data(formCustDialog, queryFilter);
    }


    @CatchErr
    @RequestMapping({"/{key}/exists"})
    public ResultMsg<Boolean> exists(@PathVariable("key") String key) {
        boolean exists = this.formCustDialogManager.existsByKey(key);
        return new ResultMsg(Boolean.valueOf(exists));
    }


    protected String getModelDesc() {
        return "FormCustDialog";  //自定义对话框
    }
}
